﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using Microsoft.CloudSaver.Web.Infrastructure;

namespace Microsoft.CloudSaver.Web.Components
{
    public partial class Users : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            usersGrid.DataSource = Membership.GetAllUsers().Cast<MembershipUser>()
                .Select(p=> new {Username=p.UserName,Email=p.Email,Password="xxx",Abilitato=p.IsApproved,Creato=p.CreationDate.ToShortDateString()});
            usersGrid.DataBind();
        }

        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (Membership.GetUser(txtUsername.Text.ToLower()) != null || txtUsername.Text.ToLower()=="cloudsaver") args.IsValid = false;
        }

        protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (!string.IsNullOrEmpty(Membership.GetUserNameByEmail(txtEmail.Text))) args.IsValid = false;
        }

        protected void cmdInsert_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                var user = Membership.CreateUser(txtUsername.Text, txtPassword.Text, txtEmail.Text);
                Roles.AddUserToRole(user.UserName, optRoles.SelectedValue);
                //CloudUtils.SetValue(user.UserName, "Area", "Undefined");
                Response.Redirect("~/Admin/Admin.aspx");
            }
        }

        protected void usersGrid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {       
                //It disables the user deletion if currently logged in.
                if (Page.User.Identity.Name==e.Row.Cells[1].Text) e.Row.Cells[e.Row.Cells.Count - 1].Text = "";
            }
        }
    }
}